package com.peixian.system.service.impl;

import com.peixian.constant.LoginConstant;
import com.peixian.enums.UserResultEnums;
import com.peixian.exception.UserException;
import com.peixian.pojo.Result;
import com.peixian.pojo.StatusCode;
import com.peixian.system.mapper.UserInfoMapper;
import com.peixian.system.pojo.UserInfo;
import com.peixian.system.service.UserService;
import com.peixian.token.TokenDTO;
import com.peixian.util.MD5Utils;
import com.peixian.util.RSACoderUtils;
import com.peixian.util.RedisPrivateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author KwokChiKit
 * @date 2021/3/19 13:59
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public String getPublicKey(String username) {
        return RedisPrivateUtil.getPublicKey(LoginConstant.getLoginKey(username), redisTemplate);
    }

    @Override
    public Result login(String username, String password) {
        //获取私匙key
        String loginKey = LoginConstant.getLoginKey(username);
        //用私钥解密密码，返回的是密码明文
        String privateKey = RedisPrivateUtil.getPrivateKey(loginKey, redisTemplate);
        //私钥解密密码后md5加密
        String newPassword = MD5Utils.MD5(RSACoderUtils.decryptPassword(password.replaceAll(" ", "+"), privateKey));
        //查询user表有无该用户
        UserInfo user = userInfoMapper.findUserByUsernameAndPassword(username, newPassword);
        if (user == null) {
            throw new UserException(UserResultEnums.USER_ACCOUNT_OR_PASSWORD__ERROR);
        }
        if (user.getStatus() == 0) {
            throw new UserException(UserResultEnums.NO_ACCOUNT);
        }
        //创建会话对象
        Long timestamp = System.currentTimeMillis();
        //生成Token
        String token = RSACoderUtils.encryptToken(new TokenDTO(user.getId(), timestamp, user.getPhone()));
        // 删除缓存中的私钥
        redisTemplate.delete(RedisPrivateUtil.PRIVATE_KEY + loginKey);

        redisTemplate.opsForValue().set(token, user.getUsername(),30, TimeUnit.DAYS);


        //封装成登录传输对象
        return new Result(true, StatusCode.OK,"登录成功",token);
    }

}
